/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2011-2012 www.pretty-tools.com
 */

var wwwPrettyTools_VKontakteButtonToollbar = {
    TOOLBAR_BUTTON_ID: "VKontakte_Button_Pretty_Tools",
    DIV_ID: "ButtonVKontakteByPrettyToolsDiv",
    API_URL: "http://vk.com/share.php?url=",
    GET_VOTES_URL: "http://vk.com/share.php?act=count&index=0&url=",
    SUCCESSFULLY_INSTALLED_URL: "http://vkontakte.pretty-tools.com/installed_for_firefox.php",
    BUTTON_CONTAINER_ID: "vkshare0"
};

wwwPrettyTools_VKontakteButtonToollbar.onLoad = function(event)
{
    try
    {
        window.addEventListener("pageshow", function(e) {
            wwwPrettyTools_VKontakteButtonToollbar.onPageShow(e);
        }, false);

        gBrowser.mTabContainer.addEventListener("select", function(e) {
            wwwPrettyTools_VKontakteButtonToollbar.updateToolbarButton();
        }, false);

        if (wwwPrettyTools_VKontakteButtonConfiguration.isFirstStart()) { // execute following only one time just after installation
            // add button to navigation panel
            this.installButtonOnToolbar();
            // need to open page with instructions
            setTimeout(function() {
                // open page with instructions
                gBrowser.selectedTab = gBrowser.addTab(wwwPrettyTools_VKontakteButtonToollbar.SUCCESSFULLY_INSTALLED_URL);
            }, 2000);
        }
    }
    catch(ex)
    {
        dump("Exception during onLoad: " + ex + "\n");
    }
}

wwwPrettyTools_VKontakteButtonToollbar.installButtonOnToolbar = function ()
{
    try
    {
        var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
        if (btn) // button exists
            return;

        // let's add it
        var navBar = document.getElementById("nav-bar");
        if (!navBar)
            return;

        var currentSet = navBar.getAttribute("currentset");
        if (!currentSet)
            currentSet = navBar.currentSet;

        var curSet = currentSet.split(",");
        if (curSet.indexOf(this.TOOLBAR_BUTTON_ID) == -1)
        {
            var set = curSet.concat(this.TOOLBAR_BUTTON_ID);
            navBar.setAttribute("currentset", set.join(","));
            document.persist("nav-bar", "currentset");
        }

        navBar.insertItem(this.TOOLBAR_BUTTON_ID);
    }
    catch(ex)
    {
        dump("Exception during installButtonOnToolbar: " + ex + "\n");
    }
}

wwwPrettyTools_VKontakteButtonToollbar.onPressButton = function ()
{
    try
    {
        var doc = window.content.document;

        if (!doc || !doc.location || !doc.location.href || !doc.location.href.match(/^http/))
            return;

        var url = this.API_URL + encodeURIComponent(doc.location.href);

        if (!wwwPrettyTools_VKontakteButtonConfiguration.isOpenInPopup())
            gBrowser.selectedTab = gBrowser.addTab(url);
        else
        {
            var left = (screen.width / 2) - (300);
            var top = (screen.height / 2) - (200);

            window.open(url, "_blank", "top="+top+",left="+left+",width=600,height=400,resizable=1");
        }
    }
    catch(e)
    {
        dump("Exception during onPressButton: " + e + "\n");
    }
}

wwwPrettyTools_VKontakteButtonToollbar.parseVotesResponse = function (txt)
{
    try
    {
        if (!txt)
            return "";

        var idx = txt.indexOf(",");
        if (idx == -1)
            return "";

        var idx2 = txt.indexOf(')', idx + 1);
        if (idx2 == -1)
            return "";

        var votes = txt.substring(idx + 1, idx2).replace(/^\s+/,'');

        for (var i = votes.length-3; i > 0; i -= 3)
            votes = votes.substr(0, i) + " " + votes.substr(i);

        return (votes.length > 0 && votes.length <= 16) ? votes : "";
    }
    catch(ex)
    {
        return null;
    }
}

wwwPrettyTools_VKontakteButtonToollbar.cacheVotesFromButton = function (doc)
{
    try
    {
        var buttonContainer = doc.getElementById(this.BUTTON_CONTAINER_ID);
        if (!buttonContainer)
            return;

        if (!buttonContainer.rows || !buttonContainer.rows.length
                || !buttonContainer.rows[0].cells || !buttonContainer.rows[0].cells.length || buttonContainer.rows[0].cells.length < 4)
            return;

        var votes = buttonContainer.rows[0].cells[3].textContent.replace(/^\s+/,'');
        if (isNaN(votes))
            return;

        for (var i = votes.length-3; i > 0; i -= 3)
            votes = votes.substr(0, i) + " " + votes.substr(i);

        if (votes.length > 0 && votes.length <= 16)
            this.cacheVotes(doc, votes);
    }
    catch(ex)
    {
    }
}

wwwPrettyTools_VKontakteButtonToollbar.onPageShow = function (event)
{
    try
    {
        var doc = event.target;

        var href = doc.location.href;

        if (!href.match(/^http/) || !(event.originalTarget instanceof HTMLDocument))
            return;

        if (!!event.originalTarget.defaultView.frameElement) // skip frames
            return;

        this.cacheVotesFromButton(doc);

        if (wwwPrettyTools_VKontakteButtonConfiguration.getShowVotes() == 2 // always get votes
                    && !doc.getElementById(this.DIV_ID) /* Not yet cached */)
        {
            var req = new XMLHttpRequest();
            req.open('GET', this.GET_VOTES_URL + encodeURIComponent(href), true);

            try {
                req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_ANONYMOUS;
            } catch (e) {
            }

            req.onreadystatechange = function (evt)
            {
                if (req.readyState != 4 || req.status != 200)
                    return;

                try
                {
                    var votes = wwwPrettyTools_VKontakteButtonToollbar.parseVotesResponse(req.responseText);

                    wwwPrettyTools_VKontakteButtonToollbar.cacheVotes(doc, votes);
                    wwwPrettyTools_VKontakteButtonToollbar.updateToolbarButton();
                }
                catch(ex)
                {
                }
            };

            req.send(null);
        }

        this.updateToolbarButton();
    }
    catch(ex)
    {
        dump("Exception during onPageShow: " + ex + "\n");
    }
}

wwwPrettyTools_VKontakteButtonToollbar.updateToolbarButton = function ()
{
    try
    {
        var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
        if (!btn)
            return;

        var div = window.content.document.getElementById(this.DIV_ID);
        if (!div || wwwPrettyTools_VKontakteButtonConfiguration.getShowVotes() == 0)
        {
            btn.setAttribute("label", "");
        }
        else
        {
            var txt = div.innerText;

            if (txt == "0" && !wwwPrettyTools_VKontakteButtonConfiguration.isShowZeros())
                txt = "";

            btn.setAttribute("label", txt);
        }
    }
    catch(e)
    {
        dump("Exception during updateToolbarButton: " + e + "\n");
    }
}

wwwPrettyTools_VKontakteButtonToollbar.cacheVotes = function (doc, votes)
{
    try
    {
        if (votes == null)
            return;

        var div = null;
        if (!(div = doc.getElementById(this.DIV_ID)))
        {
            div = doc.createElement('div');
            div.id = this.DIV_ID;
            // hide button
            div.style.position = "absolute";
            div.style.filter = "alpha(opacity: 0)";
            div.style.opacity = "0";
            div.style.zIndex = "-1";
            div.style.width = "1px";
            div.style.maxWidth = "1px";
            div.style.height = "1px";
            div.style.maxHeight = "1px";
            div.style.top = "0";
            div.style.left = "0";

            doc.body.appendChild(div);
        }
        div.innerText = votes;
    }
    catch(ex)
    {
        dump("Exception during cacheVotes: " + ex + "\n");
    }
}

try
{
    addEventListener("load", function(event) {
        try {
            wwwPrettyTools_VKontakteButtonToollbar.onLoad(event);
        } catch(ex) {
            dump("Exception on inilializing VKontakteButtonToollbar.js: " + ex + "\n");
        }
    }, false);
}
catch(ex)
{
    dump("Exception on inilializing VKontakteButtonToollbar.js: " + ex + "\n");
}
